﻿using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;

namespace Client
{
    public class Program
    {
        /// <summary>
        /// IdentityModel包括一个与发现端点一起使用的客户端库。这样，您只需要知道IdentityServer的基地址-可以从元数据中读取实际的端点地址：
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        /// 

        //找到授权的服务器
        public static async System.Threading.Tasks.Task Main(string[] args)
        {

            //找到授权服务器
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5001");  //异步的方法名前边必须声明 async
            if (disco.IsError)
            {
                Console.WriteLine($"连接失败****{disco.Error}");
                return;
            }


            //向授权服务器请求 token
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId = "client",
                ClientSecret = "secret",
                Scope = "api1"
            });
            if (tokenResponse.IsError)
            {
                Console.WriteLine("token返回错误", tokenResponse.Error);
                return;
            }
            Console.WriteLine(tokenResponse.Json);


            //将访问令牌发送给 API
            var apiClient = new HttpClient();
            apiClient.SetBearerToken(tokenResponse.AccessToken);

            var response = await apiClient.GetAsync("http://localhost:6001/test");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
                Console.WriteLine("访问失败");
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine("访问成功");
                // Console.WriteLine(JArray.Parse(content));
                Console.WriteLine(content);
            }

            Console.ReadLine();
        }

    }
}
